package cn.k7g.alloy.core.objectmapper;

import cn.k7g.alloy.annotation.AlloyContent;
import cn.k7g.alloy.exception.AlloyContentDecodeException;
import cn.k7g.alloy.exception.AlloyMessageException;
import cn.k7g.alloy.expose.AlloyContentHandler;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 反序列化alloyContent
 * @author victor-wu
 * @date 2024年4月3日
 */
@Component
@Scope(ConfigurableBeanFactory. SCOPE_PROTOTYPE)
public class AlloyContentDeserializer extends JsonDeserializer<Object> {
    private AlloyContent alloyContent;
    private AlloyContentHandler alloyContentHandler;
    private Class dataType;

    @Autowired
    private BeanFactory beanFactory;


    public AlloyContentDeserializer(AlloyContent alloyContent, Class dataType) {
        this.alloyContent = alloyContent;
        this.dataType = dataType;
    }

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        AlloyContentHandler handler = getHandler();
        try {
            return handler.decodeObject(jsonParser.getValueAsString(), dataType);
        } catch (AlloyContentDecodeException e) {
            throw new AlloyMessageException(e);
        }
    }

    public AlloyContentHandler getHandler() {
        if (alloyContentHandler == null) {
            alloyContentHandler = AlloyContentHandler.newInstance(beanFactory, alloyContent);
        }
        return alloyContentHandler;
    }
}
